package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author stone
 * @date 2022/12/23 15:46
 */
@RestController
@RequestMapping("upload")
public class UploadController {

    @RequestMapping("file")
    public BaseRespVo file(MultipartFile myfile) {
        uploadSingleFile(myfile);
        return BaseRespVo.ok();
    }
    // Ctrl + Alt + M
    private void uploadSingleFile(MultipartFile myfile) {
        String name = myfile.getName(); // myfile
        String originalFilename = myfile.getOriginalFilename(); //如果上传的是banner.png → banner.png
        String contentType = myfile.getContentType(); // image/png
        long size = myfile.getSize();
        // 比如我们要保存到D:\tmp路径下，保存的文件名叫banner.png ，我们就要提供一个这样的File
        //File file = new File("D:\\tmp\\banner.png");
        //File file = new File("D:\\tmp\\","banner.png");
        // 保存时以原始的文件名保存，如果上传同名文件会覆盖 → JavaEE  hashcode和uuid
        File file = new File("D:\\tmp\\",originalFilename);
        try {
            myfile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("files")
    public BaseRespVo files(MultipartFile[] myfiles) {
        for (MultipartFile myfile : myfiles) {
            uploadSingleFile(myfile);
        }
        return BaseRespVo.ok();
    }
}
